<template>
  <div class="add-wrap">
    <div class="project">
      <el-form
        :model="basicForm"
        label-position="top"
        :rules="basicRules"
        ref="basicFormRef"
      >
        <!-- 报征范围 -->
        <div class="project-part">
          <div class="project-part-title">报征范围</div>
          <el-row>
            <el-col>
              <el-form-item label="文件类型">
                <el-radio-group
                  v-model="fileType"
                  :disabled="isDetail"
                >
                  <el-radio label="geojson"></el-radio>
                  <el-radio label="shp"></el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row
            :gutter="24"
            v-if="fileType === 'geojson'"
          >
            <el-col :span="24">
              <el-form-item
                label="报征范围文件（geojson格式）"
              >
                <el-input
                  v-model="basicForm.geojson"
                  placeholder="请输入"
                  :disabled="isDetail"
                ></el-input>
                <el-button
                  size="small"
                  class="preview-button"
                  @click="previewMap"
                  >地图预览</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24" v-if="fileType === 'shp'">
            <el-col :span="24">
              <el-form-item label="报征范围文件（shp格式）">
                <el-upload
                  action="#"
                  class="shp-upload"
                  :show-file-list="false"
                  :drag="false"
                  :on-change="onFileSelect"
                  :auto-upload="false"
                  v-if="!isDetail"
                  accept=".zip"
                >
                  <span>
                    <span class="shp-upload-icon"></span>
                    <span class="shp-upload-text"
                      >点击上传</span
                    >
                  </span>
                </el-upload>
                <el-input
                  v-model="basicForm.fileName"
                  placeholder="暂无文件"
                  :disabled="isDetail"
                  clearable
                ></el-input>
                <el-progress
                  v-if="
                    progressNum !== 0 && progressNum !== 100
                  "
                  :percentage="progressNum"
                  color="#409eff"
                ></el-progress>
                <el-button
                  size="small"
                  class="preview-button"
                  @click="previewMap"
                  >地图预览</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>

    <customizeDialog
      :visible="dialogMapVisible"
      @update:visible="dialogMapVisible = $event"
      ref="dialog"
      :title="`${headerTitle}`"
      :titleTip="`当前面积：${currentArea}m²`"
      :width="'1200px'"
      top="100px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :has-footer="false"
      customPadding="0px"
    >
      <div
        v-loading="mapLoading"
        element-loading-text="文件正在解析中，请稍后..."
      >
        <MapView
          :viewer-id="viewerId"
          :key="countMapLoad"
          @onload="onMapLoad"
        />
        <Utool
          :viewerId="viewerId"
          :position="{ top: '60px', right: '20px' }"
          :t="[]"
          :b="[
            {
              title: '初始位置',
              icon: 'dingwei'
            }
          ]"
          :showMore="false"
        ></Utool>
      </div>
    </customizeDialog>
  </div>
</template>

<script>
import MapView from '@/components/mapView'
import Utool from '@/components/utool/index-land'
import customizeDialog from '@/components/checkHistory/customizeDialog.vue'
import { dwgFileById } from '@/api/projectMessage'
import * as turf from '@turf/turf'
import { landUseOptions } from '@/utils/project/data'
import request from '@/utils/request'

let _layerManager, _viewer

export default {
  props: {
    pkid: String,
    title: String,
    data: Object,
    isEdit: {
      type: Boolean,
      default: false
    },
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  components: {
    MapView,
    Utool,
    customizeDialog
  },
  data() {
    return {
      basicForm: {
        geojson: ''
      },
      basicRules: {},
      props: { multiple: true },
      uploadLoading: false,
      progressNum: 0,
      dialogMapVisible: false,
      mapLoading: false,
      headerTitle: '',
      countMapLoad: 0,
      currentFeature: '',
      currentArea: 0,
      fileType: 'geojson',
      viewerId: 'dwgMap'
    }
  },
  computed: {
    titles() {
      return [this.title]
    },
    landUseOptions() {
      return landUseOptions
    }
  },
  watch: {},
  mounted() {
    if (this.pkid) {
      // this.basicForm = JSON.parse(JSON.stringify(this.data))
      // this.basicForm.landUsage =
      //   this.data.landUsage.split(',')
    }
  },
  methods: {
    // 上传文件
    onFileSelect(file) {
      console.log('file', file)
      this.uploadLoading = true
      const data = new FormData()
      data.append('file', file.raw)
      request({
        method: 'post',
        url: '/pad/common/importData',
        data: data,
        onUploadProgress: (progressEvent) => {
          this.progressNum = parseInt(
            ((progressEvent.loaded / progressEvent.total) *
              100) |
              0,
            10
          )
        }
      })
        .then((res) => {
          if (res.success) {
            const id = res.data.fileId
            const geojson = res.data.geoJson
            this.$set(this.basicForm, 'fileName', file.name)
            this.$set(this.basicForm, 'shpFile', id)
            this.$set(this.basicForm, 'shpJson', geojson)
            this.$set(this.basicForm, 'geojson', geojson)
            this.$message.success('上传成功')
          } else {
            this.$message.error(res.message)
          }

          this.uploadLoading = false
        })
        .catch(() => {
          this.uploadLoading = false
        })
    },

    // 地图预览
    previewMap() {
      if (this.basicForm.shpFile) {
        this.previewMapById(
          this.basicForm.shpFile,
          this.basicForm.shpJson
        )
        this.dialogMapVisible = true
      } else if (this.basicForm.geojson) {
        this.viewByGeojson()
        this.dialogMapVisible = true
      } else {
        this.$message.warning('请先上传文件再预览')
      }
    },

    // 通过文件id预览
    previewMapById(id, geojsonStr) {
      this.headerTitle = '地图预览'
      this.mapLoading = true

      if (!geojsonStr) {
        dwgFileById(id)
          .then((res) => {
            if (res.success) {
              this.currentFeature = JSON.parse(res.data)
              const area = turf.area(this.currentFeature)
              this.currentArea = area ? area.toFixed(2) : 0
              // 更新地图预览
              this.countMapLoad++
            }
            this.mapLoading = false
          })
          .catch(() => {
            this.mapLoading = false
          })
      } else {
        this.currentFeature = JSON.parse(geojsonStr)
        const area = turf.area(this.currentFeature)
        this.currentArea = area ? area.toFixed(2) : 0
        // 更新地图预览
        this.countMapLoad++
        this.mapLoading = false
      }
    },

    // 通过geojson预览
    viewByGeojson() {
      this.currentFeature = JSON.parse(
        this.basicForm.geojson
      )
      const area = turf.area(this.currentFeature)
      this.currentArea = area ? area.toFixed(2) : 0
      // 更新地图预览
      this.countMapLoad++
      this.mapLoading = false
    },

    // 地图加载
    onMapLoad({ id, viewer }) {
      _viewer = viewer

      _viewer.scene.imageryLayers.addImageryProvider(
        new Cesium.TiandituImageryProvider({
          mapStyle: null,
          token: 'a49a9220798216424e34b531cb3fa5b2',
          url: 'https://t0.tianditu.gov.cn/img_w/wmts'
        }),
        0
      )
      const geojson = _viewer.dataSources.add(
        Cesium.GeoJsonDataSource.load(this.currentFeature)
      )
      _viewer.flyTo(geojson)
    },

    getGeoJson() {
      return this.basicForm.geojson
    }
  },
  watch: {
    'basicForm.fileName': function (val) {
      if (val === '') {
        this.basicForm.shpFile = ''
        this.basicForm.shpJson = ''
        this.basicForm.geojson = ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
.add-wrap {
  .shp-upload {
    cursor: pointer;
    height: 0px;
    ::v-deep .el-upload {
      position: relative !important;
      right: 0 !important;
      top: 0 !important;
      transform: none !important;
    }

    &-text {
      position: absolute;
      top: -49px;
      left: 260px;
      color: #00baff;
      min-width: 60px;
      line-height: 14px;
    }

    &-icon {
      position: absolute;
      width: 16px;
      height: 14px;
      top: -49px;
      left: 240px;
      background: url('~@/assets/images/wisdom-construction/upload-file.png');
      background-size: 100% 100%;
    }
  }

  .preview-button {
    position: absolute;
    top: 5px;
    left: 330px;
    background: #497fa3;
    border: 1px solid #497fa3;
    border-radius: 2px;
    color: white;
  }

  .line {
    display: flex;
    justify-content: center;
  }
}
</style>
